package com.andaily.web.controller.validator;

import com.andaily.domain.dto.user.ForgotPasswordDTO;
import com.andaily.domain.shared.MatchUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @author Shengzhao Li
 */
public class ForgotPasswordValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(ForgotPasswordDTO.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ForgotPasswordDTO forgotPasswordDTO = (ForgotPasswordDTO) target;

        validateEmail(errors, forgotPasswordDTO);

    }

    private void validateEmail(Errors errors, ForgotPasswordDTO forgotPasswordDTO) {
        String email = forgotPasswordDTO.getEmail();
        if (StringUtils.isBlank(email)) {
            errors.rejectValue("email", null, "邮箱不能为空");
        } else {
            if (!MatchUtils.isEmail(email)) {
                errors.rejectValue("email", null, "邮箱格式错误");
            }
        }

    }

}
